345. Reverse Vowels of a String

Given a string s, reverse only all the vowels in the string and return it.

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases.

1. Examples

Example 1:

Input: s = "hello"
Output: "holle"

Example 2:

Input: s = "leetcode"
Output: "leotcede"

2. Constraints

  • 1 <= s.length <= 3 * 105
  • s consist of printable ASCII characters.

3. References

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/reverse-vowels-of-a-string 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

4. Solutions

双指针

class Solution {
    public String reverseVowels(String s) {
        ArrayList<Character> list = new ArrayList<>();
        list.add('a');
        list.add('e');
        list.add('i');
        list.add('o');
        list.add('u');
        list.add('A');
        list.add('E');
        list.add('I');
        list.add('O');
        list.add('U');

        char[] chars = s.toCharArray();

        int tail = chars.length;

        for (int head = 0; head < chars.length && head < tail; head++) {
            if (list.contains(chars[head])) {
                while (!list.contains(chars[tail - 1])){
                    tail--;
                }
                char tmp = chars[tail - 1];
                chars[tail - 1] = chars[head];
                chars[head] = tmp;
                tail--;
            } else {
                continue;
            }
        }

        return new String(chars);

    }
}
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2023-03-05 10:55:51

results matching ""

    No results matching ""